﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections;
using System.Collections.Generic;
namespace MMMaze

{
    public static class DependencyObjectExtention
    {
       public static  T Clone<T>(this T source) where T : DependencyObject
        {


            DependencyObject proj = (DependencyObject)Activator.CreateInstance(source.GetType());
            foreach (var dp in GetTypeProperties(source))
            {
                proj.SetValue(dp, source.GetValue(dp));
            
            }
           
            return (T)proj;
        }

    


        static private System.Collections.Generic.Dictionary<Type, List<DependencyProperty>> PropertyCache = new Dictionary<Type, List<DependencyProperty>>();

        static public  List<DependencyProperty> GetTypeProperties(this DependencyObject obj)
        {
            var tp = obj.GetType();
            List<DependencyProperty> rval = null;
            if (!PropertyCache.TryGetValue(tp, out  rval))
            {
                var ls = new List<System.Reflection.FieldInfo>(tp.GetFields());
                rval = new List<DependencyProperty>();
                for (var i = 0; i < ls.Count; i++)
                {
                    var itm = ls[i];
                    if (itm.FieldType == typeof(DependencyProperty))
                    {
                        rval.Add((DependencyProperty)itm.GetValue(obj));
                    }
                }

                PropertyCache.Add(tp, rval);
            }

            return rval;
        }

    }
}
